package boc.sx.gateway.core.strategy;

import boc.sx.gateway.core.ServiceNode;
import javafx.util.Pair;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.PriorityQueue;

/*
 * @author zmx
 * @date 2022/8/9 16:16
 */
@Component
@LBStrategy(1)
public class PollingLB implements LoadBalanceStrategy {

    @Override
    public String vote(ServiceNode serviceNode) {
        String[] urls = serviceNode.getUri();
        if(urls.length ==0){
            return null;
        }
        else if(urls.length==1){
            addCount(urls[0]);
            return urls[0];
        }else{
            // 执行轮训策略
            PriorityQueue<Pair<String,Integer>> queue = new PriorityQueue<Pair<String,Integer>>(Comparator.comparingInt(Pair::getValue));
            for(String url:urls){
                Pair s = new Pair(url, getCount(url));
                queue.add(s);
            }
            Pair<String, Integer> peek = queue.peek();
            addCount(peek.getKey());
            return peek.getKey();
        }
    }
}
